/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import { ProjectImpl } from '../base/internal/lifecycle/hvigor-node-impl/project-impl.js';
import { Json5Reader } from '../base/util/json5-reader.js';
import { ProjectStructureOpt } from '../base/common/options/project-structure-opt.js';
import path from 'path';

/**
 * 记录模块配置的来源
 * 目前模块可以从 build-profile 里面配置 和 hvigorconfig 文件里动态配置
 */
class NodeConfigPathInfo {
  private nodeConfigPath: Map<string, string> = new Map();
  private excludeNodes: string[] = [];
  private buildProfilePath: string = '';

  // 标记是否使用includeNode,excludeNodeByName等动态修改配置
  private isModuleChanged = false;

  addModuleConfigPath(moduleName: string, rootDir: string) {
    this.nodeConfigPath.set(moduleName, path.resolve(rootDir, 'hvigorconfig.ts'));
    this.isModuleChanged = true;
  }

  deleteModuleConfigPath(moduleName: string) {
    this.excludeNodes.push(moduleName);
    this.nodeConfigPath.delete(moduleName);
    this.isModuleChanged = true;
  }

  initNodeConfigPath(project: ProjectImpl) {
    this.nodeConfigPath.clear();
    this.isModuleChanged = false;
    this.excludeNodes = [];
    this.buildProfilePath = project.getProject().getBuildProfilePath();
    const projectStructureOpt: ProjectStructureOpt = Json5Reader.getJson5Obj(this.buildProfilePath);
    const moduleOpts = projectStructureOpt?.modules;
    if (moduleOpts) {
      moduleOpts.forEach((module) => {
        this.nodeConfigPath.set(module.name, this.buildProfilePath);
      });
    }
  }

  getNodeConfigPathByName(nodeName: string) {
    return this.nodeConfigPath.get(nodeName) ?? this.buildProfilePath;
  }

  checkExcludeNode(nodeName: string) {
    return this.excludeNodes.some((name) => name === nodeName);
  }

  getIsModuleChanged() {
    return this.isModuleChanged;
  }
}

export const nodeConfigPathInfo = new NodeConfigPathInfo();
